package calendar;

import edu.gmu.client.FrontEnd;
import edu.gmu.messages.EndPoint;
import edu.gmu.middleware.Message;
import edu.gmu.streams.BlockInputStream;
import edu.gmu.streams.BlockOutputStream;
import java.io.IOException;

/**
 * This class represents a single user
 */
public class User implements Message, Comparable
{
    private int id;
    private String name;
    private EndPoint endpoint;

    public User( )
    {
        this(0, "", null);
    }
    
    public User( int id, String name )
    {
        this(id, name, null);
    }
    
    public User( int id, String name, EndPoint endpoint )
    {
        this.id       = id;
        this.name     = name;
        this.endpoint = endpoint;
    }
    
    /**
     * Factory method to create a new user with a unique id.  Note that this
     * will not work with hash-lookup mechanism.
     * @param name
     * @param users (used to ensure no duplicate is created)
     * @return
     */
    public static User makeUser( String name )
    {
        int id = FrontEnd.hashName(name);
        return new User( id, name );
    }

    public int getId()
    {
        return this.id;
    }

    public String getName()
    {
        return new String ( this.name );
    }

    public void setName( String name )
    {
        this.name = new String( name );
    }

    public EndPoint getEndPoint()
    {
        return this.endpoint;
    }

    public void setEndPoint( EndPoint endpoint )
    {
        this.endpoint = endpoint;
    }
    
    /**
     * Determines if this user is equal to another user
     * @param stream
     * @throws java.io.IOException
     */
    public boolean equals( Object obj )
    {
        if( obj == this ) return true;
        
        if( !(obj instanceof User) ) return false;
        User o = (User)obj;
        
        // Only check id - small chance id's are different and names equal
        return this.name.equals( o.name );
    }

    public void marshal(BlockOutputStream stream) throws IOException
    {
        stream.writeInt( id );
        stream.writeUTF( name );
        boolean isNull = (this.endpoint == null);
        stream.writeBoolean(isNull);
        if( isNull == false )
        {
            this.endpoint.marshal(stream);
        }
    }
    public void unmarshal(BlockInputStream stream) throws IOException
    {
        this.id   = stream.readInt();
        this.name = stream.readUTF();
        if( stream.readBoolean() == false )
        {
            this.endpoint = new EndPoint();
            this.endpoint.unmarshal(stream);
        }
    }

    public String toString()
    {
        return this.name + "-"+this.id;
    }

  public int compareTo(Object o) {
    return name.compareTo( ((User)o).getName() );
  }
}
